package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.aliyuncs.exceptions.ClientException;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Order;
import com.itheima.service.OrderService;
import com.itheima.utils.SMSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderController {

    //注入redis
    @Autowired
    private JedisPool jedisPool;

    //使用远程注入服务层
    @Reference
    private OrderService orderService;

    /*
        预约提交
     */
    @RequestMapping("/submit")
    public Result submit(@RequestBody Map map) {
        //从数据中获取手机号
        String telephone = (String) map.get("telephone");
        //从数据中获取验证码
        String validateCode = (String) map.get("validateCode");
        //从redis中获取缓存的实际的验证码,与页面中填写的进行比较
        String codeInRedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_ORDER);

        if (validateCode == null || !validateCode.equals(codeInRedis)) {
            //如果输入的验证码为空或者与redis中缓存的验证码不相等
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }

        Result result = null;
        //验证码校验通过
        try {
            //在map中添加预约类型
            map.put("orderType", Order.ORDERTYPE_WEIXIN);
            //调用服务层
            result = orderService.order(map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ORDERSETTING_FAIL);
        }

        //根据返回的result判断是否预约成功
        if (result.isFlag()) {
            String orderDate = (String) map.get("orderDate");

            try {
                //预约成功,发送短信
                SMSUtils.sendShortMessage(SMSUtils.ORDER_NOTICE, telephone, orderDate);
            } catch (ClientException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    @RequestMapping("/findById")
    public Result findById(int id) {
        //调用服务层
        Map map = orderService.findById4Detail(id);
        return new Result(true, MessageConstant.ORDER_SUCCESS, map);
    }
}
